import {inject, observer} from "mobx-react";
import React from 'react';
import {toJS} from 'mobx';
import {Row, Col, Input, Tabs, Button, Alert, Spin, Icon, Form, Modal, Switch, Radio} from 'antd';
import {WeaTop, WeaTab, WeaRightMenu, WeaNewScroll, WeaSearchGroup, WeaInput, WeaSelect, WeaTools,
  WeaErrorPage, WeaRichText, WeaDialog, WeaPopoverHrm, WeaFormItem, WeaLocaleProvider
} from 'ecCom';
import {WeaSwitch, WeaTableNew} from 'comsMobx';
const {WeaTable} = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
import BasicSetting from './Setting/BasicSetting/index';
import ShareSetting from './Setting/ShareSetting/index';
import CreateModule from './Setting/ModuleSetting/CreateModule';
import EditModule from './Setting/ModuleSetting/EditModule';
import PreviewModule from './Setting/ModuleSetting/PreviewModule';
import * as blogUtil from '../util/index';

@inject('blogSetting')
@observer
class Setting extends React.Component {
  constructor(props) {
    super(props);
    this.formP ={};
  }

  componentDidMount() {
    this.props.blogSetting.doInit();
  }

  componentWillReceiveProps(nextProps) {
    if(this.props.location.key !== nextProps.location.key) {
      this.props.blogSetting.doInit();
    }
  }

  componentWillUnmount() {
    //组件卸载时一般清理一些状态
    const {blogSetting} = this.props;
    blogSetting.changeTab(0);
    this.setState({moudledefaultid: ''});
  }

  getSearchs = (onEnterSearch,ecId) => {
    const { moduleForm, moduleStatus } = this.props.blogSetting;
    const fields = moduleStatus.moduleFields;
    const {isFormInit} = moduleForm;
    let group = [];
    const formParams = moduleForm.getFormParams();

     for (let i in formParams){
       this.formP[i] = formParams[i];
     }


    isFormInit && fields && fields.map((c,i) =>{
      let items = [];
      c.items.map(fields => {
        if(onEnterSearch && typeof onEnterSearch === 'function' && fields.conditionType==='INPUT'){
          fields.onEnterSearch=onEnterSearch;
        }
        items.push({
          com:(<WeaFormItem ecId={`${ecId}_WeaFormItem@py7e6k@${fields.domkey[0]}`}
            label={`${fields.label}`}
            labelCol={{span: 8}}
            wrapperCol={{span: 16}}>
            <WeaSwitch ecId={`${ecId}_WeaSwitch@soew34@${fields.domkey[0]}`} fieldConfig={fields} form={moduleForm} formParams={this.formP}/>
          </WeaFormItem>),
          col: 2
        })
      });
      group.push(<WeaSearchGroup ecId={`${ecId}_WeaSearchGroup@2c7qj1@${i}`} needTigger={true} showGroup={c.defaultshow} items={items}/>)
    });
    return group;
  }

  getTabButtonsAd(ecId) {
    const {blogSetting} = this.props;
    return [
      (<Button ecId={`${ecId}_Button@ilar2t@search`} type="primary" onClick={() => {blogSetting.getBlogDefaultTemplate(true); blogSetting.setModuleState({showSearchAd: false})}}>{getLabel(197,"搜索")}</Button>),
      (<Button ecId={`${ecId}_Button@w8uxrf@reset`} type="ghost" onClick={() => blogSetting.moduleForm.reset()}>{getLabel(2022,"重置")}</Button>),
      (<Button ecId={`${ecId}_Button@3zw581@cancel`} type="ghost" onClick={() => blogSetting.setModuleState({showSearchAd: false})}>{getLabel(31129,"取消")}</Button>)
    ]
  }

  getRightMenu = () => {
    const {blogSetting} = this.props
    const {tabkey, moduleTableStore} = blogSetting;
    const moudleSelectedRowKeys = toJS(moduleTableStore.selectedRowKeys);
    let btns = [];
    if (tabkey == 0) {
      btns.push({
        key: 'BTN_BASESAVE',
        icon: <i className='icon-coms-Preservation'/>,
        content: getLabel(30986,"保存"),
        onClick : () => this.save()
      });
    }
    if (tabkey == 2) {
      btns.push(
        // {
        //   key: 'BTN_SAVE',
        //   icon: <i className='icon-coms-Preservation'/>,
        //   content: getLabel(30986,"保存"),
        //   onClick: () => this.moduleRightMenuClick('BTN_SAVE')
        // },
        {
          key: 'BTN_NEW',
          icon: <i className='icon-coms-New-Flow'/>,
          content: getLabel('365',"新建"),
          onClick: () => this.moduleRightMenuClick('BTN_NEW')
        },
        {
          key: 'BTN_DEL',
          icon: <i className='icon-coms-Batch-delete'/>,
          content: getLabel('32136',"批量删除"),
          disabled: moudleSelectedRowKeys.length == 0,
          onClick: () => this.moduleRightMenuClick('BTN_DEL'),
        },
        {
          key: 'BTN_LIST',
          icon: <i className='icon-coms-Custom'/>,
          content: getLabel(382660,"显示定制列"),
          onClick: () => this.moduleRightMenuClick('BTN_LIST'),
        }
      );
    }
    return btns;
  }

  getBtns(ecId) {
    const {blogSetting} = this.props;
    const {tabkey, moduleTableStore, baseStatus} = blogSetting;
    const moudleSelectedRowKeys = toJS(moduleTableStore.selectedRowKeys);
    if (tabkey == 0) {
      return [(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ca06pr@blog${tabkey+ecId}`} type="primary" loading={baseStatus.baseSaveLoading} onClick={() => this.save()}>{getLabel(30986,"保存")}</Button>)];
    }
    if (tabkey == 1) {
      return [];
    }
    if (tabkey == 2) {
      return [
        //(<Button type="primary" onClick={() => this.moduleRightMenuClick('BTN_SAVE')}>{getLabel(30986,"保存")}</Button>),
        (<Button ecId={`${ecId}_Button@na2awu@newcreate`} type="primary" onClick={() => this.moduleRightMenuClick('BTN_NEW')}>{getLabel('365',"新建")}</Button>),
        (<Button ecId={`${ecId}_Button@mve64g@deletebatch`} type="primary" disabled={moudleSelectedRowKeys.length == 0} onClick={() => this.moduleRightMenuClick('BTN_DEL')}>{getLabel('32136',"批量删除")}</Button>),
      ];
    }
  }

  moduleRightMenuClick = (type) => {
    const {blogSetting} = this.props;
    const moudleSelectedRowKeys = toJS(blogSetting.moduleTableStore.selectedRowKeys);
    if (type == 'BTN_SAVE') {//保存
      blogSetting.setUserBlogTemplateToDefault({defaultBtId: blogSetting.moduleStatus.defaultBtId});
    }
    if (type == "BTN_NEW") {//新建
      blogSetting.getBlogTemplateAddCondition();
      blogSetting.setModuleState({showCreate: true});
    }
    if (type == 'BTN_DEL') {//批量删除
      blogUtil.doConfirm(getLabel(82017,'确认删除？'), () => blogSetting.operateBlogTemplateSet({operation: 'deleteTemp', id: moudleSelectedRowKeys.join(',')}));
    }
    if(type == 'BTN_LIST'){//显示列定制
      blogSetting.moduleTableStore.setColSetVisible(true);
      blogSetting.moduleTableStore.tableColSet(true);
    }
  }

  //第一个页签的保存按钮功能
  save = () => {
    const {blogSetting} = this.props;
    blogSetting.saveBlogUserSetting({isReceive: blogSetting.baseStatus.checked});
  }

  onOperatesClick = (record, index, operate) => {
    const {blogSetting} = this.props;
    if(operate.index == '0'){//编辑
      this.doEditCommon(record);
      blogSetting.setModuleState({selectedKey: 0});
    }
    if(operate.index == '1') {//模版内容设置
      this.doEditCommon(record);
      blogSetting.setModuleState({selectedKey: 1});
    }
    if(operate.index == '2') {//模版预览
      blogSetting.getBlogTemplateContent({tempid: record.randomFieldId});
      blogSetting.setModuleState({showPreview: true});
    }
    if(operate.index == '3') {//共享烦范围
      this.doEditCommon(record);
      blogSetting.setModuleState({selectedKey: 2});
    }
    if(operate.index == '4') {//删除
      blogUtil.doConfirm(getLabel(82017,'确认删除？'), () => blogSetting.operateBlogTemplateSet({operation: 'deleteTemp', id: record.randomFieldId}));
    }
  }

  doEditCommon = (record) => {
    const {blogSetting} = this.props;
    blogSetting.setModuleState({editId: record.randomFieldId});
    blogSetting.doEditInit(record.randomFieldId);
    blogSetting.getBlogTemplateAddCondition({id:record.randomFieldId});
    blogSetting.setModuleState({showEdit: true});
  }

  //自定义过滤渲染
  getNewColumns = (columns) => {
    const {blogSetting} = this.props;
    const {defaultBtId} = blogSetting.moduleStatus;
    return columns.map((column,index) => {
      let newColumn = {...column};
      newColumn.render = (text, record, index) => { //前端元素转义
        let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
        if(newColumn.dataIndex == 'defaultIdColunm'){
          return <Radio ecId={`${this && this.props && this.props.ecId || ''}_Radio@3etik0@${index+newColumn.dataIndex}`} type={'checkbox'}
                        name='isDefault'
                        checked={defaultBtId == record.randomFieldId}
                        onChange={(e) => {
                          if(defaultBtId == record.randomFieldId){
                            $(this).removeAttr("checked");
                            blogSetting.setModuleState({defaultBtId: ''});
                            blogSetting.setUserBlogTemplateToDefault({defaultBtId: ''});
                          }else {
                            blogSetting.setModuleState({defaultBtId: record.randomFieldId});
                            blogSetting.setUserBlogTemplateToDefault({defaultBtId: record.randomFieldId});
                          }
                        }}/>
        }
        if (newColumn.dataIndex == 'tempName') {
          let opentype = record.isPrev; //0编辑，1预览
          return (
            <a title={text} onClick={() => {
              if(opentype == 0){
                this.doEditCommon(record);
                blogSetting.setModuleState({selectedKey: 0});
              }else {
                blogSetting.getBlogTemplateContent({tempid: record.randomFieldId});
                blogSetting.setModuleState({showPreview: true});
            }}}
            dangerouslySetInnerHTML={{__html: valueSpan}}/>
          )
        } else {
          return (
            <div className="wea-url" dangerouslySetInnerHTML={{__html: valueSpan}}/>
          )
        }
      }
      return newColumn;
    });
  }



  onEnterSearch = () => {
      const {blogSetting} = this.props;
      blogSetting.getBlogDefaultTemplate(true)
  }

  render() {
    const {blogSetting} = this.props;
    const {title, tabkey, tabDatas, moduleStatus} = blogSetting;
    const collectParams={
      favname: title,
      favouritetype: 1,
      objid:0,
      link:'wui/engine.html#/blogengine/setting',
      importantlevel: 1,
    };

    return (
      <div className='wea-blog-setting' style={{height: "100%", overflow: "hidden"}}>
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@0zenp2`}
          datas={this.getRightMenu()}
          collectParams={{collectParams}}
        >
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@qc2whx`}
            icon={<span className='icon-coms-blog'/>}
            iconBgcolor="#6d3cf7"
            title={title}
            buttons={this.getBtns(this.props.ecId || '')}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            dropMenuProps={{collectParams: collectParams}}
          />
          <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@pkqunn`}
            selectedKey={tabkey}
            datas={tabDatas}
            keyParam='key'
            onChange={e => blogSetting.changeTab(e)}
            searchType={tabkey == 2 ? ['base', 'advanced'] : ''}
            searchsBaseValue={blogSetting.moduleForm.getFormParams().tempName}
            setShowSearchAd={bool => blogSetting.setModuleState({showSearchAd: bool})}
            hideSearchAd={() =>  blogSetting.setModuleState({showSearchAd: false})}
            buttonsAd={this.getTabButtonsAd(this.props.ecId || '')}
                  advanceHeight = {120}
            showSearchAd={moduleStatus.showSearchAd}
            searchsAd={this.getSearchs(this.onEnterSearch,this.props.ecId || '')}
            onSearch={() => blogSetting.getBlogDefaultTemplate(true)}
            onSearchChange={v => blogSetting.moduleForm.updateFields({tempName: {value: v}})}
          />
          {tabkey == 0 ?
            <BasicSetting ecId={`${this && this.props && this.props.ecId || ''}_BasicSetting@s0iups`}/>
            : tabkey == 1 ?
              <ShareSetting ecId={`${this && this.props && this.props.ecId || ''}_ShareSetting@hbftdp`}/>
              :
              <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@1r04t6`}
                comsWeaTableStore={blogSetting.moduleTableStore}
                hasOrder={true}
                needScroll={true}
                getColumns={this.getNewColumns}
                onOperatesClick={this.onOperatesClick}
              />
          }
        </WeaRightMenu>
        <CreateModule ecId={`${this && this.props && this.props.ecId || ''}_CreateModule@n0fs43`}/>
        <EditModule ecId={`${this && this.props && this.props.ecId || ''}_EditModule@v20wzv`}/>
        <PreviewModule ecId={`${this && this.props && this.props.ecId || ''}_PreviewModule@3zucfm`}/>
        <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@qb81ov`}/>
      </div>
    )
  }
}

//组件检错机制
class MyErrorHandler extends React.Component {
  render() {
    const hasErrorMsg = this.props.error && this.props.error !== "";
    return (
      <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@sxwed6`} msg={hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！"}/>
    );
  }
}

Setting = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(Setting);
export default (Setting);